/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.command;

import java.util.Map;
import java.util.Set;

import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.uml2.uml.InteractionFragment;
import org.eclipse.uml2.uml.InteractionOperand;

import com.cea.papyrus.diagram.sequence.sedi.model.command.DelegatingCommand;
import com.cea.papyrus.diagram.sequence.sedi.model.command.SetOwnerCommand;


/**
 * This command takes a CombinedFragment and a number of sets, one for each
 * operand, that contains the fragments that should be adoped by that 
 * operand. The command is equal to a number of SetOwnerCommands.
 * 
 * <p>The following attributes must be set for the command to complete
 * successfully:</p>
 * <ul>
 *   <li>Capture
 * </ul>
 * 
 * @author frankd@ifi.uio.no
 *
 * @see com.cea.papyrus.diagram.sequence.sedi.model.command.ReleaseContainedFragmentsCommand
 */
public class CaptureCoveredFragmentsCommand extends CompoundCommand {
	
	// The strategy we have adopted is to reserve one command - a 
	// DelegatingCommand - at instantiation time. This command is
	// populated with the real SetOwnerCommands at execution time.
	// 
	// This strategy should not violate any particular design decisions
	// in the Eclipse framework about how commands are executed.
	
	private Map<InteractionOperand, Set<InteractionFragment>> capture;

	private DelegatingCommand setOwnerCommands;

	public CaptureCoveredFragmentsCommand() {
		add(new Command() {
			public void execute() {
				CompoundCommand cmds = new CompoundCommand();
	
				for (InteractionOperand operand : capture.keySet()) {
					Set<InteractionFragment> fragments = capture.get(operand);
					for (InteractionFragment f : fragments) {
						SetOwnerCommand setOwnerCmd = new SetOwnerCommand();
						setOwnerCmd.setFragment(f);
						setOwnerCmd.setOwner(operand);
						cmds.add(setOwnerCmd);
					}
				}
				
				setOwnerCommands.setCommand(cmds);
			}
		});
		
		setOwnerCommands = new DelegatingCommand();
		add(setOwnerCommands);
	}

	public void setCapture(
			final Map<InteractionOperand, Set<InteractionFragment>> capture) {
		this.capture = capture;
	}
	
	@Override
	public void dispose() {
		setOwnerCommands = null;
		capture = null;
		super.dispose();
	}	
}
